<template>
  <div class="codegen-service">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>微服务代码生成</span>
        </div>
      </template>
      
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="service-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="服务名称" prop="serviceName">
              <el-input
                v-model="form.serviceName"
                placeholder="请输入服务名称，如：order"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务描述" prop="serviceDescription">
              <el-input
                v-model="form.serviceDescription"
                placeholder="请输入服务描述，如：订单服务"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="包名" prop="packageName">
              <el-input
                v-model="form.packageName"
                placeholder="请输入包名，如：com.wzh"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生成路径" prop="generatePath">
              <el-input
                v-model="form.generatePath"
                placeholder="请输入生成路径，如：/tmp/codegen"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input
                v-model="form.author"
                placeholder="请输入作者名称"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">生成选项</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item>
              <el-checkbox v-model="form.includeApi">包含API模块</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-checkbox v-model="form.includeSwagger">包含Swagger文档</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-checkbox v-model="form.includeFeign">包含Feign客户端</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item>
          <el-button type="primary" @click="generateCode" :loading="generating">
            <el-icon><Document /></el-icon>
            生成代码
          </el-button>
          <el-button type="success" @click="downloadCode" :loading="downloading">
            <el-icon><Download /></el-icon>
            下载代码
          </el-button>
          <el-button @click="resetForm">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 生成结果 -->
    <el-card v-if="generateResult" class="box-card result-card">
      <template #header>
        <div class="card-header">
          <span>生成结果</span>
        </div>
      </template>
      
      <el-alert
        :title="generateResult"
        type="success"
        :closable="false"
        show-icon
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Document, Download, Refresh} from '@element-plus/icons-vue'
import {codegenApi, type CodegenServiceDTO} from '@/api/codegen'
import {downloadFile} from '@/utils/download'

// 表单引用
const formRef = ref()

// 表单数据
const form = reactive<CodegenServiceDTO>({
  serviceName: '',
  serviceDescription: '',
  packageName: 'com.wzh',
  generatePath: '/tmp/codegen',
  author: 'wzh',
  includeApi: true,
  includeSwagger: true,
  includeFeign: true
})

// 表单验证规则
const rules = {
  serviceName: [
    { required: true, message: '请输入服务名称', trigger: 'blur' },
    { pattern: /^[a-z][a-z0-9-]*[a-z0-9]$/, message: '服务名称只能包含小写字母、数字和连字符，且必须以字母开头和结尾', trigger: 'blur' }
  ],
  serviceDescription: [
    { required: true, message: '请输入服务描述', trigger: 'blur' }
  ],
  packageName: [
    { required: true, message: '请输入包名', trigger: 'blur' },
    { pattern: /^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*$/, message: '包名格式不正确', trigger: 'blur' }
  ],
  generatePath: [
    { required: true, message: '请输入生成路径', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者名称', trigger: 'blur' }
  ]
}

// 状态
const generating = ref(false)
const downloading = ref(false)
const generateResult = ref('')

// 生成代码
const generateCode = async () => {
  try {
    await formRef.value?.validate()
    
    generating.value = true
    const { data } = await codegenApi.generateService(form)
    generateResult.value = data
    ElMessage.success('代码生成成功')
  } catch (error: any) {
    console.error('生成代码失败:', error)
    ElMessage.error(error.message || '生成代码失败')
  } finally {
    generating.value = false
  }
}

// 下载代码
const downloadCode = async () => {
  try {
    await formRef.value?.validate()
    
    await ElMessageBox.confirm(
      '确认下载代码压缩包？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    downloading.value = true
    const response = await codegenApi.downloadService(form)
    downloadFile(response, `${form.serviceName}.zip`)
    ElMessage.success('下载成功')
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('下载失败:', error)
      ElMessage.error(error.message || '下载失败')
    }
  } finally {
    downloading.value = false
  }
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  generateResult.value = ''
}
</script>

<style scoped>
.codegen-service {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.service-form {
  max-width: 800px;
}

.result-card {
  margin-top: 20px;
}

:deep(.el-divider__text) {
  font-weight: bold;
  color: var(--el-text-color-primary);
}
</style>